//
//  EFSChartAdapter.m
//  EFSMobile
//
//  Created by Chuan on 11/18/15.
//  Copyright © 2015 Elephants Financial Service. All rights reserved.
//

#import "EFSChartAdapter.h"
#import "NSUserDefaults+YS.h"
#import "YSServiceManager.h"
#import "YSUserManager.h"

#import <YTXRequest/YTXRequest.h>
#import "YSRequestConfig.h"

#import "YTXChart.h"
#import <DateTools/DateTools.h>


using namespace ytx;
using namespace std;

@implementation EFSChartAdapter

+ (nonnull instancetype) sharedAdapter
{
    static EFSChartAdapter * sharedAdapter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedAdapter = [[EFSChartAdapter alloc] initConfigAndData: NO];
    });
    return sharedAdapter;
}

- (void) configChartStyle:(ytx::YTXConfig *) config
{
    config->style.defaultRed = "#EB333B";
    config->style.defaultGreen = "#17B03E";
    config->style.defaultWhite = "#000000";
    //背景色
    config->style.backColor = "#FFFFFF";//
    //矩形框内背景色
    config->style.rectColor = "#FFFFFF";//矩形框背景颜色
    config->style.rectLineColor = "#DDDDDD";//矩形边框线颜色
    config->style.rectLineWidth = 0.5;
    
    //十字线
    config->style.crosshairsColor = "#E6000000";//
    config->style.crosshairsWidth = 1;
    config->style.crosshairsTextColor = "#EB333B";//
    config->style.crosshairsTextBackgorundColor = "#F4F4F4";//
    config->style.crosshairsTextLineWidth = 1;
    
    config->style.coordinateColor = "#DDDDDD";//网格线
    config->style.coordinateWidth = 0.5;
    
    config->style.sideTextColor = "#2B2F33";//
    config->style.textColor = "#666666";//
    
    //avg
    config->style.isAvgValueShadowColor = false;
    config->style.avgValueColor = "#626262";//k线颜色
    config->style.avgAVEColor = "#FFBB33";//
    config->style.avgValueShadowColor = "#4C2887EE";//k线阴影
    config->style.avgOfVolumeColor = "#464c56";//持平状态
    
    //财经日历
    config->style.AVGEconomicCalendarFillColorDefault = "#AAAAAA";//
    config->style.AVGEconomicCalendarFillColorSelected = "#FFBB33";//
    config->style.AVGEconomicCalendarTextColor = "#FFFFFF";//
    
    config->style.rectPaddingRight = 0;
    
    config->style.userPaintDefaultColor = "#2987ee";//
    
}

- (instancetype) initConfigAndData:(BOOL) isTest
{
    self = [super init];
    if(self)
    {
        ytx::YTXConfig * config = ytx::YTXConfig::getInstance();
        config->isTest = isTest;
        config->userDefaultGroupName = [[NSUserDefaults userDefaultGroup] UTF8String];
        config->style.init(1);
        
        if (isTest) {
            config->metal = ytx::Metal::initCollection();
        }
        
        [self configChartStyle:config];
        
        
        ytx::AVGDataList * avgDataList = ytx::AVGDataList::getInstance(config->metal, config->AVG.type);
        
        ytx::KLineDataList::getInstance(config->metal, avgDataList);
        
        
        //以前的changeConfig
        [self configUrls];
        
        //setUserInfo
        
        //用户切换 断开socket
        
//        [[[RACSignal combineLatest:@[
//                                     RACObserve([YSServiceManager sharedServiceManager], currentServerId),
//                                     RACObserve([YSUserManager sharedManager], currentUser.token)]] distinctUntilChanged] subscribeNext:^(id x) {
//            
//            UserInfo * userInfoInstance = UserInfo::getInstance();
//            
//            UserAccountType * usertype = [YSUserManager sharedManager].currentUser.userType;
//            
//            if (usertype == nil) {
//                usertype = @(0);
//            }
//            
//            userInfoInstance->setUsernameAndServerId([objectOrEmptyStr([YSUserManager sharedManager].currentUser.username) UTF8String], [[YSServiceManager sharedServiceManager].currentServerId longValue] );
//            userInfoInstance->setHasPhone( [YSUserManager sharedManager].currentUser.hasPhone );
//            userInfoInstance->setUserType( (int)[usertype integerValue] );
//            
//        }];
        
        [self clearAllIndexPermission];
        
    }
    return self;
}

- (void) configUrls
{
        ytx::YTXConfig * config = ytx::YTXConfig::getInstance();
    
        config->communicate.mtdataRouting = [[[YSRequestConfig shared] urlStringFromName:@"quotation.TodayKline"] UTF8String];
    
        config->communicate.hisKdataRouting = [[[YSRequestConfig shared] urlStringFromName:@"quotation.HisKline"] UTF8String];
    
//        config->communicate.dkdataRouting = [[[YTXRequestConfig sharedYTXRequestConfig] urlStringFromName:@"quotes.apiurl"] UTF8String];
//    
//        config->communicate.mkdataRouting = [[[YTXRequestConfig sharedYTXRequestConfig] urlStringFromName:@"quotes.apiurl"] UTF8String];
}

- (void) clearAllIndexPermission
{
    AVGDataList * avgDataList = AVGDataList::getInstance();
    
    KLineDataList * kLineDataList = KLineDataList::getInstance();
    
    for (AVGDataList::iterator it = avgDataList->begin(); it != avgDataList->end(); ++it) {
        (*it)->clearAllIndexPermission();
    }
    
    for (KLineDataList::iterator it = kLineDataList->begin(); it != kLineDataList->end(); ++it) {
        (*it)->clearAllIndexPermission();
    }
}

- (void) clearAllIndexPermissionWithQuoteId:(nonnull NSString *)quoteId
{
    AVGDataList * avgDataList = AVGDataList::getInstance();
    
    KLineDataList * kLineDataList = KLineDataList::getInstance();
    
    AVGData * avgData = avgDataList->get([quoteId UTF8String]);
    
    if (avgData) {
        avgData->clearAllIndexPermission();
    }
    
    KLineData * kLineData;
    
    for(int i = LineType::L5m;i != LineType::EMPTY;i++){
        LineType::LineType qType = static_cast<LineType::LineType>(i);
        kLineData = kLineDataList->get([quoteId UTF8String], qType);
        if (kLineData) {
            kLineData->clearAllIndexPermission();
        }
    }
}

- (void) changeIndexPermission:(nonnull NSString *) sid withLineType:(nonnull NSString *) lineTypeStr withIndexType:(nonnull NSString *) indexTypeStr  withPermission:(int)permission
{
    LineType::LineType lineType = LineType::convertLineTypeFromString([lineTypeStr UTF8String]);
    IndexType::IndexType indexType =  IndexType::ConvertIndexTypeFromString([indexTypeStr UTF8String]);
    int indexPermission = permission;
    
    if (lineType == LineType::LAVG || indexType == IndexType::LSP) {
        AVGData * data = AVGDataList::getInstance()->get([sid UTF8String]);
        data->addIndexPermission(indexType, indexPermission);
    }
    else {
        KLineData * data = KLineDataList::getInstance()->get([sid UTF8String], lineType);
        // 初级有权限
        if (indexType == IndexType::HJJTJC || indexType == IndexType::HJJTGJ || indexType == IndexType::HJJTZX) {
            IndexConfig indexConfig = data->getIndexConfig(IndexType::HJJT);
            int permissionUser = indexConfig.getIndexPermission();
            if (indexType == IndexType::HJJTJC && (indexPermission == HJJTJCPermissionBehaviorType::ForHasPermission || indexPermission == HJJTJCPermissionBehaviorType::Trial)) {
                if (permissionUser == HJJTPermissionBehaviorType::ForNoPermission) {
                    data->addIndexPermission(IndexType::HJJT, HJJTPermissionBehaviorType::ForJC);
                }
            }
            else if (indexType == IndexType::HJJTGJ && (indexPermission == HJJTJCPermissionBehaviorType::ForHasPermission || indexPermission == HJJTJCPermissionBehaviorType::Trial) && permissionUser < HJJTPermissionBehaviorType::ForGJ) {
                data->addIndexPermission(IndexType::HJJT, HJJTPermissionBehaviorType::ForGJ);
            }
            else if (indexType == IndexType::HJJTZX && (indexPermission == HJJTJCPermissionBehaviorType::ForHasPermission || indexPermission == HJJTJCPermissionBehaviorType::Trial) && permissionUser < HJJTPermissionBehaviorType::ForZX) {
                data->addIndexPermission(IndexType::HJJT, HJJTPermissionBehaviorType::ForGJ);
            }
            else {
                if (permissionUser == HJJTPermissionBehaviorType::ForNoPermission) {
                    data->addIndexPermission(IndexType::HJJT, HJJTPermissionBehaviorType::ForNoPermission);
                }
                
            }
        }
        else {
            data->addIndexPermission(indexType, indexPermission);
        }
    }
    
}

- (void) changeAllIndexConfigs:(NSString *)sid withIndexConfig:(NSDictionary *) configDict
{
    //avg
    for(int j = LineType::L5m;j != LineType::EMPTY;j++){
        LineType::LineType qType = static_cast<LineType::LineType>(j);
        [self changeIndexConfig:sid withLineType:qType withIndexConfig:configDict];
    }
}

- (void) changeIndexConfig:(NSString *)sid withIndexConfig:(NSDictionary *) configDict
{
    //avg
    if ( [configDict objectForKey:@"lineType"] ) {
        LineType::LineType qType = LineType::convertLineTypeFromString([[configDict objectForKey:@"lineType"] UTF8String]);
        [self changeIndexConfig:sid withLineType:qType withIndexConfig:configDict];
    }
}

- (void) updateQuotePrice:(YSSecurities *) quote
{
    if (quote == nil) return;
    AVGData * data = AVGDataList::getInstance()->get([quote.IdStr UTF8String]);
    if (data) {
        //self.viewModel.totalTradeVolume withValue:self.viewModel.totalTradeAmount withAvg:self.viewModel.avgPx
        if (quote.IdStr && quote.UpdTm && quote.OpenPx && quote.LatestPx && quote.HighPx && quote.LowPx) {
            double volume = quote.TotalTradeVolume == nil? 0 : [quote.TotalTradeVolume doubleValue];
            double value = quote.TotalTradeAmount == nil? 0 : [quote.TotalTradeAmount doubleValue];
            double hold = quote.OpenInt == nil? 0 : [quote.OpenInt doubleValue];
            double avg = quote.AvgPx == nil? 0 : [quote.AvgPx doubleValue];
            data->updateQuotedPrice([quote.IdStr UTF8String], [quote.UpdTm.stringValue UTF8String], [quote.OpenPx doubleValue], [quote.LatestPx doubleValue], [quote.HighPx doubleValue], [quote.LowPx doubleValue], volume, value, hold, avg);
        }
    }
}

- (void) changeIndexConfig:(NSString *)sid withLineType:(LineType::LineType) lineType withIndexConfig:(NSDictionary *) configDict
{
    KLineData * data = KLineDataList::getInstance()->get([sid UTF8String], lineType);
    
    std::string id_string = "";
    
    std::string lineType_string = "";
    
    std::string indexType_string = "";
    
    std::string indexChartTypeType_string = "";
    
    vector<string> type;
    
    vector<string> name;
    
    vector<double> value;
    
    vector<pair<double, double> > range;
    
    bool enabled = true;
    
    bool hasEnabled = false;
    
    vector<double> ratio;
    
    NSDictionary * args = configDict;
    
    for (NSString *key in args) {
        if ( [key  isEqual: @"id"] ) {// PMEC.GDAG
            id_string = [args[key] UTF8String];
        }
        else if ( [key  isEqual: @"indexType"] ) {// TJ
            indexType_string = [args[key] UTF8String];
        }
        else if ( [key  isEqual: @"indexChartType"] ) {// main
            indexChartTypeType_string = [args[key] UTF8String];
        }
        else if ( [key  isEqual: @"lineType"] ) {// 60m
            lineType_string = [args[key] UTF8String];
        }
        else if ( [key  isEqual: @"type"] ) {
            NSArray * type_arr = (NSArray*)args[key];
            for (id obj in type_arr) {
                NSString * t = (NSString *) obj;
                std::string t_string ([t UTF8String]);
                type.push_back(t_string);
            }
            
        }
        else if ( [key  isEqual: @"name"] ) {
            NSArray * name_arr = (NSArray*)args[key];
            for (id obj in name_arr) {
                NSString * t = (NSString *) obj;
                std::string t_string ([t UTF8String]);
                name.push_back(t_string);
            }
        }
        else if ( [key  isEqual: @"value"] ) {
            NSArray * value_arr = (NSArray*)args[key];
            for (id obj in value_arr) {
                NSNumber * t = (NSNumber *) obj;
                value.push_back(t.doubleValue);// [4]
            }
        }
        else if ( [key  isEqual: @"range"] ) {
            NSArray * range_arr = (NSArray*)args[key];
            for (id obj in range_arr) {
                NSArray * r = (NSArray*)obj;
                
                range.push_back(pair<double, double>( ((NSNumber *) r[0]).doubleValue, ((NSNumber *) r[1]).doubleValue ) );
            }
        }
        else if ( [key  isEqual: @"enabled"] ) {
            enabled = (bool)args[key];
            hasEnabled = true;
        }
        else if ( [key  isEqual: @"ratio"] ) {
            NSArray * ratio_arr = (NSArray*)args[key];
            for (id obj in ratio_arr) {
                NSNumber * t = (NSNumber *) obj;;
                ratio.push_back(t.doubleValue);// [0.0618, 0.0382, 8.27, 10.27]
            }
        }
    }
    
    // 取原值，而不用默认, data 有值，说明应用启动后设置过新的值，配置中 hasEnabled=false 说明设置为无效
    if (data && !hasEnabled) {
        enabled = data->getIndexConfig(ytx::IndexConfig::getIndexTypeByString(indexType_string)).enabled;
    }
    
    ytx::IndexConfig indexConfig = ytx::IndexConfig(ytx::IndexConfig::getIndexTypeByString(indexType_string), indexType_string, ytx::IndexConfig::getIndexChartTypeByString(indexChartTypeType_string), type, name, value, range, enabled, ratio);
    
    if (data) {
        data->getIndexConfig(indexConfig.indexType).extendSelf(indexConfig);
    }
}

//- (void) onSecurityChange: (CJQuote *) quote
//{
//    [self addMetalAsync:quote];
//}
//
//- (void) addMetalList: (CJQuoteList *) quoteList
//{
//    @weakify(self);
//    [[quoteList getQuotes] enumerateKeysAndObjectsUsingBlock:^(id key, CJQuote * quote, BOOL *stop) {
//        @strongify(self);
//        [self addMetalSync:quote];
//    }];
//}

- (void) addMetalSync: (YSSecurities *) quote
{
    if (!quote) {
        return;
    }
    NSArray *indexConfigs = @[];//P([NSString stringWithFormat:@"indexConfig.%@", quote.ID]);
    for (NSDictionary *config in indexConfigs) {
        [self changeIndexConfig:[NSString stringWithFormat:@"%@", quote.Id] withIndexConfig:config];
    }
    
    // 开休市时间
    
    int hasStepDay = 0;
    YTXTime openTime;
    YTXTime endTime;
    vector<pair<YTXTime, YTXTime> > tradeTimes;
    if (quote.TraTimeTs && quote.TraTimeTs.length > 0) {
        // 有 time_t 格式则用这个格式处理，没有则用 tradeTime 处理。
        NSArray *bonds = [quote.TraTimeTs componentsSeparatedByString:@"-"];
        openTime = YTXTime([bonds.firstObject longLongValue]);// 开市
        endTime = YTXTime([bonds.lastObject longLongValue]);// 闭市
        NSArray *timeBonds = [quote.TraTimeTs componentsSeparatedByString:@";"];
        if ( openTime.toStringYYYYMMdd() != endTime.toStringYYYYMMdd() ) {
            hasStepDay = 1;//1 表示交易日跨越多天
        }
        for (NSString *str in timeBonds) {
            bonds = [str componentsSeparatedByString:@"-"];
            tradeTimes.push_back( make_pair(YTXTime([bonds.firstObject longLongValue]), YTXTime([bonds.lastObject longLongValue])));
        }
    }
    else {
        NSDate *referenceDate = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
        NSNumberFormatter *numFmt = [NSNumberFormatter new];
        NSArray *bonds = [quote.TraTimes componentsSeparatedByString:@"-"];
        hasStepDay = [bonds containsObject:@"1440;0"]? 1 : 0;// 是否跨天
        NSDate *begin = [referenceDate dateByAddingMinutes:[numFmt numberFromString:bonds.firstObject].integerValue];
        NSDate *end = [referenceDate dateByAddingMinutes:[numFmt numberFromString:bonds.lastObject].integerValue];
        end = [self ensure:end isLaterThan:begin];
        NSString *beginStr = [begin formattedDateWithFormat:@"YYYYMMdd HH:mm:ss" timeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *endStr = [end formattedDateWithFormat:@"YYYYMMdd HH:mm:ss" timeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        
        openTime = YTXTime( [beginStr UTF8String] );// 开市
        endTime = YTXTime( [endStr UTF8String] );// 闭市
        
        // 交易时段
        NSArray *timeBonds = [quote.TraTimes componentsSeparatedByString:@";"];
        
        for (NSString *str in timeBonds) {
            
            bonds = [str componentsSeparatedByString:@"-"];
            NSDate *begin0 = [referenceDate dateByAddingMinutes:[numFmt numberFromString:bonds.firstObject].integerValue];
            begin0 = [self ensure:begin0 isLaterThan:begin];
            NSDate *end0 = [referenceDate dateByAddingMinutes:[numFmt numberFromString:bonds.lastObject].integerValue];
            end0 = [self ensure:end0 isLaterThan:begin0];
            NSString *beginStr0 = [begin0 formattedDateWithFormat:@"YYYYMMdd HH:mm:ss" timeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
            NSString *endStr0 = [end0 formattedDateWithFormat:@"YYYYMMdd HH:mm:ss" timeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
            
            string f = [beginStr0 UTF8String];
            string s = [endStr0 UTF8String];
            tradeTimes.push_back( make_pair(YTXTime(f), YTXTime(s)));
        }
    }
    string name = [quote.name UTF8String];// AbbrName
    string nickname = [quote.number UTF8String];// SecurityID
    string marketType = [quote.market UTF8String];// Market
    string id = [[quote.Id stringValue] UTF8String];// quoteId
    string currentDate = [[NSString stringWithFormat:@"%@", quote.TraDate] UTF8String];
    // timeType 交易时间类型 （1，m1，m2）
//    TimeString ts = Metal::createTimeStringByTimeType(Metal::timeTypeByTradeTime([objectOrEmptyStr(quote.TraTimes) UTF8String]));
    TimeString ts = Metal::createTimeStringBytradeTime([objectOrEmptyStr(quote.TraTimes) UTF8String]);
    
    int toFix = [quote.Decm intValue];
    
    bool hasVolume = quote.hasVolume;
    
    Metal metal = Metal::createMetal(name, nickname, marketType, id, currentDate, hasStepDay, ts, openTime, endTime, tradeTimes, Config::getInstance()->index, toFix, hasVolume);
    
    vector<Metal> metalList;
    
    metalList.push_back(metal);
    
    AVGDataList::getInstance()->create(metalList);
    
    KLineDataList::getInstance()->create(metalList, AVGDataList::getInstance());
}

- (NSDate *)ensure:(NSDate *)aDate isLaterThan:(NSDate *)earliestDate {
    if ([aDate isEarlierThan:earliestDate]) {
        return [aDate dateByAddingDays:1];
    }
    return aDate;
}

- (void) clearAllDataCache
{
    AVGDataList * avgDataList = AVGDataList::getInstance();
    
    KLineDataList * kLineDataList = KLineDataList::getInstance();
    
    for (AVGDataList::iterator it = avgDataList->begin(); it != avgDataList->end(); ++it) {
        (*it)->clearAllData();
    }
    
    for (KLineDataList::iterator it = kLineDataList->begin(); it != kLineDataList->end(); ++it) {
        (*it)->clearAllData();
    }
    QKSQLite qkSqlite;
    
    QKTSQLite qktSqlite;
    
    KLineSQLite kLineSqlite;
    
    GameMatrixSQLite gameMatrixSQLite;
    
    HJJTSQLite hjjtSQLite;
    
    //删除 数据库文件
    NSFileManager* fm = [NSFileManager defaultManager];
    [fm removeItemAtPath:[NSString stringWithUTF8String:qkSqlite.getPath().c_str()] error:nil];
    [fm removeItemAtPath:[NSString stringWithUTF8String:qktSqlite.getPath().c_str()] error:nil];
    [fm removeItemAtPath:[NSString stringWithUTF8String:kLineSqlite.getPath().c_str()] error:nil];
    [fm removeItemAtPath:[NSString stringWithUTF8String:gameMatrixSQLite.getPath().c_str()] error:nil];
    [fm removeItemAtPath:[NSString stringWithUTF8String:hjjtSQLite.getPath().c_str()] error:nil];
    
}

- (float) getCacheInfo
{
    QKSQLite qkSqlite;
    
    QKTSQLite qktSqlite;
    
    KLineSQLite kLineSqlite;
    
    GameMatrixSQLite gameMatrixSQLite;
    
    HJJTSQLite hjjtSQLite;
    
    float filesize = 0.0;
    
    NSFileManager* fm = [NSFileManager defaultManager];
    NSDictionary* qkAttrs = [fm attributesOfItemAtPath: [NSString stringWithUTF8String:qkSqlite.getPath().c_str()] error:nil];
    
    if (qkAttrs) {
        filesize += [qkAttrs[@"NSFileSize"] floatValue] / 1024.0 / 1024.0;
    }
    
    NSDictionary* qktAttrs = [fm attributesOfItemAtPath: [NSString stringWithUTF8String:qktSqlite.getPath().c_str()] error:nil];
    
    if (qktAttrs) {
        filesize += [qktAttrs[@"NSFileSize"] floatValue] / 1024.0 / 1024.0;
    }
    
    NSDictionary* kLineAttrs = [fm attributesOfItemAtPath: [NSString stringWithUTF8String:kLineSqlite.getPath().c_str()] error:nil];
    
    if (kLineAttrs) {
        filesize += [kLineAttrs[@"NSFileSize"] floatValue] / 1024.0 / 1024.0;
    }
    
    NSDictionary* gameMatrixAttrs = [fm attributesOfItemAtPath: [NSString stringWithUTF8String:gameMatrixSQLite.getPath().c_str()] error:nil];
    
    if (gameMatrixAttrs) {
        filesize += [gameMatrixAttrs[@"NSFileSize"] floatValue] / 1024.0 / 1024.0;
    }
    
    NSDictionary* hjjtAttrs = [fm attributesOfItemAtPath: [NSString stringWithUTF8String:hjjtSQLite.getPath().c_str()] error:nil];
    
    if (hjjtAttrs) {
        filesize += [hjjtAttrs[@"NSFileSize"] floatValue] / 1024.0 / 1024.0;
    }
    
    return filesize;
}

- (nonnull RACSignal *)updateCustomerCodeWithContent:(nonnull NSString *)content {
    RACReplaySubject *subject = [RACReplaySubject subject];
    
    NSDictionary *params = @{@"customer" : objectOrEmptyStr([YSUserManager sharedManager].currentUser.username),
                             @"content" : content};
    YTXRequest *request = [YTXRequest requestWithName:@"ucenter.updateCode"];
    [request sendWithParameters:params success:^(id  _Nonnull response) {
        NSDictionary *repseDict = (NSDictionary *)response;
        [subject sendNext:repseDict];
        [subject sendCompleted];
        
    } failure:^(YTXRequest * _Nonnull request) {
        NSError *error = [NSError errorWithDomain:@"YTX" code:0 userInfo:@{EFS_ERROR_MESSAGE_KEY: @"投顾邀请码激活权限"}];
        [subject sendError:error];
    }];
    
    
    return subject;
}

- (nonnull RACSignal *)requestTargetWithVarietyVersion:(nonnull NSString *)varietyVersion {
    RACReplaySubject *subject = [RACReplaySubject subject];
    
    NSDictionary *params = @{@"username" : objectOrEmptyStr([YSUserManager sharedManager].currentUser.username),
                             @"targetName" : @"HJJT",
                             @"varietyVersion" : varietyVersion,
                             @"permissionType" : @"2"};
    YTXRequest *request = [YTXRequest requestWithName:@"ucenter.requestTarget"];
    [request sendWithParameters:params success:^(id  _Nonnull response) {
        NSDictionary *repseDict = (NSDictionary *)response;
        if ([[repseDict valueForKey:@"code"] isEqual:@1]) {
            [subject sendNext:repseDict];
        } else {
            [subject sendNext:repseDict];
        }
        
        [subject sendCompleted];
        
    } failure:^(YTXRequest * _Nonnull request) {
        NSError *error = [NSError errorWithDomain:@"YTX" code:0 userInfo:@{EFS_ERROR_MESSAGE_KEY: @"通过营销页获取指标"}];
        [subject sendError:error];
    }];
    
    return subject;
}



@end
